//
//  PerInfoEditViewController.m
//  sklive
//
//  Created by Macx on 2017/6/22.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PerInfoEditViewController.h"

#import "UIButton+WebCache.h"
#import <Masonry.h>
#import "WSDatePickerView.h"
#import "CertifySelectViewController.h"


@interface PerInfoEditViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

// 相册照相机
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) NSString *imgStr;
@property (nonatomic, strong) NSString *sexT;
@property (nonatomic, strong) NSString *money;

@property (nonatomic, assign) BOOL isChangeImage;

@property (nonatomic, assign) BOOL isTeturn;

@property (nonatomic, strong) NSString *ageStr;

@property (nonatomic, strong) NSString *birthdayStr;

@property (nonatomic, strong) NSString *locationStr;
//data
@property (strong, nonatomic) NSDictionary *pickerDic;
/** 当前省数组 */
@property (strong, nonatomic) NSArray *provinceArray;
/** 当前城市数组 */
@property (strong, nonatomic) NSArray *cityArray;
/** 当前选中数组 */
@property (strong, nonatomic) NSArray *selectedArray;

@property (nonatomic, strong) NSMutableArray *ageArr;


@end

@implementation PerInfoEditViewController {
    
    UITextField             *_locationTF;
    UITextField             *_ageTF;
    
    UIView                  *_pickerBgView;
    
    UIPickerView            *_locationPicker;
    UIPickerView            *_agePicker;
    
    UIView                  *_pickerToolbgView;
    
    UIScrollView            *_scorllView;
    
}

- (void)viewWillDisappear:(BOOL)animated {
	
}

- (void)willMoveToParentViewController:(UIViewController*)parent{
    [super willMoveToParentViewController:parent];
    
    if (self.isTeturn) {
        [self isReturn];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
    self.pickerDic = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.provinceArray = [self.pickerDic allKeys];
    self.selectedArray = [self.pickerDic objectForKey:[[self.pickerDic allKeys] objectAtIndex:0]];
    if (self.selectedArray.count > 0) {
        self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
    }
    
    [self createUI];
    
    [self createImgPicker];
    
}


- (void)createUI {
    
    self.navigationItem.title = @"个人信息";
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return"] style:UIBarButtonItemStylePlain target:self action:@selector(navLeftAction:)];
    
    _scorllView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_scorllView];
    NSArray *arr = [NSArray arrayWithObjects:@"   头像", @"   昵称", @"   性别", @"   实名认证", @"   生日", @"   省市", @"   签名", nil];
    
    CGSize size = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(15)];
    
    for (int i = 0; i < arr.count; i++) {
        UILabel *label = [[UILabel alloc] init];
        [_scorllView addSubview:label];
        label = [self createLabel:label text:arr[i]];
        label.tag = 1+i;
    }
    
    UILabel *headPic = [self.view viewWithTag:1];
    headPic.frame = CGRectMake(0, 0, SCREEN_WIDTH, size.height+30);
    
    UIButton *headPicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scorllView addSubview:headPicBtn];
    headPicBtn.frame = CGRectMake(SCREEN_WIDTH-SW(20)-20-size.height, 5,  20+size.height,  20+size.height);
    headPicBtn.layer.cornerRadius = (20+size.height)/2;
    headPicBtn.layer.masksToBounds = YES;
    [headPicBtn sd_setImageWithURL:[self.userInfo valueForKey:@"face"] forState:UIControlStateNormal];
    self.imgStr = [self.userInfo valueForKey:@"face"];
    [headPicBtn addTarget:self action:@selector(headPicAction:) forControlEvents:UIControlEventTouchUpInside];
    headPicBtn.tag = 10;
    
    UILabel *nickName = [self.view viewWithTag:2];
    nickName.frame = CGRectMake(0, headPic.y+headPic.height+1, SCREEN_WIDTH, size.height+30);
    
    UITextField *nickNameTF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, 15+headPic.y+headPic.height+1, SCREEN_WIDTH-30-size.width-SW(20), size.height)];
    [_scorllView addSubview:nickNameTF];
    nickNameTF.textAlignment = NSTextAlignmentRight;
    nickNameTF.textColor = [UIColor lightGrayColor];
    nickNameTF.text = [self.userInfo valueForKey:@"nickname"];
    nickNameTF.font = kUHSystemFontWithSize(15);
    nickNameTF.tag = 11;
    nickNameTF.delegate = self;
    
    UILabel *sex = [self.view viewWithTag:3];
    sex.frame = CGRectMake(0, nickName.y+nickName.height+1, SCREEN_WIDTH, size.height+30);
    
    UIButton *sexBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scorllView addSubview:sexBtn];
    sexBtn.titleLabel.font = kUHSystemFontWithSize(15);
    [sexBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    sexBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    if ([[self.userInfo valueForKey:@"sex"] isEqualToString:@"1"]) {
        [sexBtn setTitle:@"男" forState:UIControlStateNormal];
        self.sexT = @"1";
    }
    else {
        [sexBtn setTitle:@"女" forState:UIControlStateNormal];
        self.sexT = @"2";
    }
    sexBtn.frame = CGRectMake(30+size.width, nickName.y+nickName.height+1, SCREEN_WIDTH-30-size.width-SW(20), size.height+30);
    [sexBtn addTarget:self action:@selector(sexAction:) forControlEvents:UIControlEventTouchUpInside];
    sexBtn.tag = 12;
    
    //实名认证
    UILabel *realNameCert = [self.view viewWithTag:4];
    realNameCert.frame = CGRectMake(0, sex.y+sex.height+1, SCREEN_WIDTH, size.height+30);
    UIButton *realNameCertBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-SW(11.5), realNameCert.y+13, size.height/2, size.height)];
    [realNameCertBtn setBackgroundImage:IMAGE(@"arrow_right_grey") forState:UIControlStateNormal];
	[realNameCert addTarget:self action:@selector(certifyAction:)];
    [self.view addSubview:realNameCertBtn];
    
    
    // 年龄
    UILabel *ageL = [self.view viewWithTag:5];
    ageL.frame = CGRectMake(0, realNameCert.y+realNameCert.height+1, SCREEN_WIDTH, size.height+30);
    
    
    UITextField *ageF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, ageL.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
    [_scorllView addSubview:ageF];
    ageF.delegate = self;
    ageF.textColor = kGrayColor;
    ageF.clearButtonMode = UITextFieldViewModeWhileEditing;
    ageF.font = kUHSystemFontWithSize(15);
    ageF.textAlignment = NSTextAlignmentRight;
    ageF.rightViewMode = UITextFieldViewModeAlways;
    UIImageView *imgV0 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
    ageF.rightView = imgV0;
    imgV0.image = IMAGE(@"arrow_right_grey");
    _ageTF = ageF;
    ageF.text = self.userInfo[@"birthday"];
    self.birthdayStr = self.userInfo[@"birthday"];
    self.ageStr = ageF.text;
    
    UIView *view0 = [[UIView alloc] initWithFrame:CGRectMake(ageF.x, ageF.y, ageF.width, ageF.height)];
    [_scorllView addSubview:view0];
    [view0 addActionWithblock:^{
        NSLog(@"选择日期");
        
        UITextField *tf = [self.view viewWithTag:11];
        [tf resignFirstResponder];
        UITextView *tv = [self.view viewWithTag:15];
        [tv resignFirstResponder];
        
        //        [self pickerShow:1];
        
        // 显示日期选择
        WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
            
            //            NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
            NSString *date = [NSString stringWithFormat:@"%ld年%ld月%ld日",selectDate.year,selectDate.month,selectDate.day];
            ageF.text = date;
            self.birthdayStr = date;
            
            // 获取系统当前 年月日
            NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
            NSInteger currentDateYear = [components2 year];
            NSInteger currentDateMonth = [components2 month];
            NSInteger currentDateDay= [components2 day];
            
            // 计算年龄
            NSInteger iAge = currentDateYear - selectDate.year - 1;
            if ((currentDateMonth > selectDate.month) || (currentDateMonth == selectDate.month && currentDateDay >= selectDate.day)) {
                iAge++;
            }
            self.ageStr = [NSString stringWithFormat: @"%ld",iAge];
            
            [self pickerRemove];
        }];
        
        NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
        [minDateFormater setDateFormat:@"yyyy-MM-dd"];
        NSDate *scrollToDate = [minDateFormater dateFromString:@"1930-1-1"];
        datepicker.minLimitDate = scrollToDate;
        datepicker.maxLimitDate = [NSDate date];
        [datepicker show];
    }];
    
    
    
    
    // 地区
    UILabel *location = [self.view viewWithTag:6];
    location.frame = CGRectMake(0, ageL.y+ageL.height+1, SCREEN_WIDTH, size.height+30);
    
    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, location.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
    [_scorllView addSubview:field];
    field.delegate = self;
    field.textColor = kGrayColor;
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    field.font = kUHSystemFontWithSize(15);
    field.textAlignment = NSTextAlignmentRight;
    field.rightViewMode = UITextFieldViewModeAlways;
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
    field.rightView = imgV;
    imgV.image = IMAGE(@"arrow_right_grey");
    _locationTF = field;
    field.text = self.userInfo[@"city"];
    self.locationStr = field.text;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(field.x, field.y, field.width, field.height)];
    [_scorllView addSubview:view];
    [view addActionWithblock:^{
        NSLog(@"选择城市");
        
        UITextField *tf = [self.view viewWithTag:11];
        [tf resignFirstResponder];
        UITextView *tv = [self.view viewWithTag:15];
        [tv resignFirstResponder];
        
        [self pickerShow:2];
        
    }];
    
    
    
    UILabel *sign = [self.view viewWithTag:7];
    sign.frame = CGRectMake(0, location.y+location.height+1, SCREEN_WIDTH, size.height+30);
    
    UITextView *signTV = [[UITextView alloc] init];
    [_scorllView addSubview:signTV];
    NSString *signStr = self.userInfo[@"intro"];
    //    if (signStr.length > 250) {
    //        signTV.text = [self.userInfo[@"intro"] substringFromIndex:250];
    //    }
    //    else
    signTV.text = signStr;
    signTV.textColor = [UIColor lightGrayColor];
    signTV.font = kUHSystemFontWithSize(14);
    signTV.delegate = self;
    //    signTV.adjustsFontForContentSizeCategory = YES;
    [signTV scrollRangeToVisible:NSMakeRange(0,1)];
    CGSize signSize = [signTV sizeThatFits:CGSizeMake(SCREEN_WIDTH-20-SW(20), MAXFLOAT)];
    signTV.frame = CGRectMake(0, sign.y+sign.height+1, SCREEN_WIDTH, 15+signSize.height);
    signTV.textContainerInset = UIEdgeInsetsMake(15, SW(20), 15, 20);//设置页边
    signTV.tag = 15;
    
    UILabel *proIntro = [self.view viewWithTag:8];
    //    proIntro.frame = CGRectMake(0, signTV.y+signTV.height+1, SCREEN_WIDTH, size.height+30);
    
    UITextView *proIntroTV = [[UITextView alloc] init];
    [_scorllView addSubview:proIntroTV];
    //    proIntroTV.text = [self.userInfo[@"intro"] substringFromIndex:50];
    NSString *proStr = self.userInfo[@"pro_intro"];
    //    if (proStr.length > 250) {
    //        proIntroTV.text = [self.userInfo[@"pro_intro"] substringFromIndex:250];
    //    }
    //    else
    proIntroTV.text = proStr;
    //    proIntroTV.text = self.userInfo[@"pro_intro"];
    proIntroTV.textColor = [UIColor lightGrayColor];
    proIntroTV.font = kUHSystemFontWithSize(14);
    proIntroTV.delegate = self;
    //    signTV.adjustsFontForContentSizeCategory = YES;
    [proIntroTV scrollRangeToVisible:NSMakeRange(0,1)];
    //    CGSize proIntroSize = [proIntroTV sizeThatFits:CGSizeMake(SCREEN_WIDTH-20-SW(20), MAXFLOAT)];
    //    proIntroTV.frame = CGRectMake(0, proIntro.y+proIntro.height+1, SCREEN_WIDTH, 15+proIntroSize.height);
    proIntroTV.textContainerInset = UIEdgeInsetsMake(15, SW(20), 15, 20);//设置页边
    proIntroTV.tag = 16;
    
    
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(completeAction:)];
    UIButton * right = [UIButton buttonWithType:UIButtonTypeCustom];
    [right setTitle:@"保存" forState:UIControlStateNormal];
    right.titleLabel.font = kUHSystemFontWithSize(14);
    right.frame = CGRectMake(0, 0, [LZCTools textSizeWithText:right.titleLabel.text font:right.titleLabel.font].width, 44);
    right.titleLabel.textAlignment = NSTextAlignmentRight;
    [right setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [right addTarget:self action:@selector(completeAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:right];
    
    if ([self.userInfo[@"role"] isEqualToString:@"3"]) {
        
        //        [proIntro mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.top.mas_equalTo(signTV.mas_bottom).offset(1);
        //            make.left.mas_equalTo(_scorllView).offset(0);
        //            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, size.height+30));
        //        }];
        //
        //        CGSize proIntroSize = [proIntroTV sizeThatFits:CGSizeMake(SCREEN_WIDTH-20-SW(20), MAXFLOAT)];
        //        [proIntroTV mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.top.mas_equalTo(proIntro.mas_bottom).offset(1);
        //            make.left.mas_equalTo(_scorllView).offset(0);
        //            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 15+proIntroSize.height));
        //        }];
        
        proIntro.frame = CGRectMake(0, signTV.y+signTV.height+1, SCREEN_WIDTH, size.height+30);
        CGSize proSize = [proIntroTV sizeThatFits:CGSizeMake(SCREEN_WIDTH-20-SW(20), MAXFLOAT)];
        proIntroTV.frame = CGRectMake(0, proIntro.y+proIntro.height+1, SCREEN_WIDTH, 15+proSize.height);
        
        _scorllView.contentSize = CGSizeMake(SCREEN_WIDTH, proIntroTV.y+proIntroTV.height);
        //        _scorllView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
		proIntroTV.hidden = YES;
		proIntro.hidden = YES;
    }
    else {
        proIntroTV.hidden = YES;
        proIntro.hidden = YES;
    }
    
    _pickerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [_scorllView addSubview:_pickerBgView];
    _pickerBgView.backgroundColor = RGBA(0, 0, 0, 0.2);
    _pickerBgView.hidden = YES;
    
    //初始化mainPickView
    _locationPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, SH(3))];
    [_scorllView addSubview:_locationPicker];
    _locationPicker.delegate = self;
    _locationPicker.dataSource = self;
    _locationPicker.backgroundColor = UISeparatedColorRGB;
    _locationPicker.showsSelectionIndicator = YES;
    
    //初始化mainPickView
    _agePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, SH(3))];
    //    [_scorllView addSubview:_agePicker];
    //    _agePicker.delegate = self;
    //    _agePicker.dataSource = self;
    _agePicker.backgroundColor = UISeparatedColorRGB;
    _agePicker.showsSelectionIndicator = YES;
    
    _agePicker.hidden = YES;
    _locationPicker.hidden = YES;
    
    _pickerToolbgView = [[UIView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
    [_scorllView addSubview:_pickerToolbgView];
    _pickerToolbgView.backgroundColor = UISeparatedColorRGB;
    
    NSArray *arr2 = @[@"取消", @"确定"];
    for (int i = 0; i < arr2.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pickerToolbgView addSubview:btn];
        [btn setTitle:arr2[i] forState:UIControlStateNormal];
        [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
        btn.titleLabel.font = kUHSystemFontWithSize(12);
        if (i==0) {
            btn.frame = CGRectMake(0, 0, 50, 40);
            [btn addTarget:self action:@selector(pickerRemove) forControlEvents:UIControlEventTouchUpInside];
        }
        else {
            btn.frame = CGRectMake(SCREEN_WIDTH-50, 0, 50, 40);
            [btn addTarget:self action:@selector(priceBtnText) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 1)];
    [_pickerToolbgView addSubview:line];
    line.backgroundColor = kLightGrayColor;
     
    
}

- (UILabel *)createLabel:(UILabel *)label text:(NSString *)text {
    
    label.textColor = [UIColor grayColor];
    label.text = text;
    label.font = kUHSystemFontWithSize(15);
    label.backgroundColor = kWhiteColor;
    
    return label;
}



#pragma mark ==========UIPickerView==========
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    //    return 2; // 返回1表明该控件只包含1列
    
    if ([pickerView isEqual:_agePicker]) {
        return 1;
    }
    else {
        return 2;
    }
}
//UIPickerViewDataSource中定义的方法，该方法的返回值决定该控件指定列包含多少个列表项
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // 由于该控件只包含一列，因此无须理会列序号参数component
    // 该方法返回books.count，表明books包含多少个元素，该控件就包含多少行
    //    return self.pickerArr.count;
    if ([pickerView isEqual:_agePicker]) {
        return self.ageArr.count;
    }
    else {
        if (component == 0) {
            return self.provinceArray.count;
        } else {
            return self.cityArray.count;
        }
    }
}
// UIPickerViewDelegate中定义的方法，该方法返回的NSString将作为UIPickerView
// 中指定列和列表项的标题文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    // 由于该控件只包含一列，因此无须理会列序号参数component
    // 该方法根据row参数返回books中的元素，row参数代表列表项的编号，
    // 因此该方法表示第几个列表项，就使用books中的第几个元素
    //    return [self.pickerArr objectAtIndex:row];
    if ([pickerView isEqual:_agePicker]) {
        return [self.ageArr objectAtIndex:row];
    }
    else {
        if (component == 0) {
            return [self.provinceArray objectAtIndex:row];
        } else {
            return [self.cityArray objectAtIndex:row];
        }
    }
}
// 当用户选中UIPickerViewDataSource中指定列和列表项时激发该方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //    [_priceSortedBtn setTitle:self.pickerArr[row] forState:UIControlStateNormal];
    //    self.pickerStr = self.pickerArr[row];
    if ([pickerView isEqual:_locationPicker]) {
        
        if (component == 0) {
            self.selectedArray = [self.pickerDic objectForKey:[self.provinceArray objectAtIndex:row]];
            if (self.selectedArray.count > 0) {
                self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
            } else {
                self.cityArray = nil;
            }
            //        [pickerView selectRow:1 inComponent:1 animated:YES];
        }
        [pickerView selectedRowInComponent:1];
        [pickerView reloadComponent:1];
        //    [pickerView selectedRowInComponent:2];
    }
    
    
}

- (void)priceBtnText {
    
    if (_agePicker.isHidden == NO) {
        self.ageStr = [self.ageArr objectAtIndex:[_agePicker selectedRowInComponent:0]];
        _ageTF.text = self.ageStr;
        [self pickerRemove];
    }
    else {
        NSString *p = [self.provinceArray objectAtIndex:[_locationPicker selectedRowInComponent:0]];
        NSString *c = [self.cityArray objectAtIndex:[_locationPicker selectedRowInComponent:1]];
        
        self.locationStr = [NSString stringWithFormat:@"%@%@", p, c];
        
        _locationTF.text = self.locationStr;
        
        [self pickerRemove];
    }
    
}

- (void)pickerShow:(NSInteger)picker {
    if (picker == 1) {
        _agePicker.hidden = NO;
    }
    else {
        _locationPicker.hidden = NO;
    }
    _pickerBgView.hidden = NO;
    [UIView animateWithDuration:0.33 animations:^{
        _pickerToolbgView.y = SH(3)*2-104;
        _locationPicker.y = SH(3)*2-64;
        _agePicker.y = SH(3)*2-64;
    } completion:^(BOOL finished) {
    }];
    
}
- (void)pickerRemove {
    
    [UIView animateWithDuration:0.33 animations:^{
        _pickerToolbgView.y = 2*SCREEN_HEIGHT;
        _locationPicker.y = 2*SCREEN_HEIGHT;
        _agePicker.y = 2*SCREEN_HEIGHT;
    } completion:^(BOOL finished) {
        _pickerBgView.hidden = YES;
        _agePicker.hidden = YES;
        _locationPicker.hidden = YES;
    }];
}

#pragma mark ==========响应方法==========
- (void)navLeftAction:(id)sender {
    if (self.isTeturn) {
        [self isReturn];
    }
    else
        [self.navigationController popViewControllerAnimated:YES];
}

- (void)isReturn {
    NSLog(@"++++++%d", self.isTeturn);
    
    if (self.isTeturn) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否放弃修改？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"返回上一层" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.isTeturn = 0;
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"保存修改内容" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self completeAction:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    
}

//- (void)textFieldDidChange:(UITextField *)textField
//{
//    if (textField == [self.view viewWithTag:11]) {
//        if (textField.text.length > 10) {
//            [self presentViewController:[LZCTools alertMessage:@"昵称不可以超过10字"] animated:YES completion:nil];
//            return;
//        }
//    }
//}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    self.isTeturn = 1;
    
    //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if ([self.view viewWithTag:11] == textField)  //判断是否时我们想要限定的那个输入框
    {
        if ([toBeString length] > 20) { //如果输入框内容大于20则弹出警告
            textField.text = [toBeString substringToIndex:8];
            [self presentViewController:[LZCTools alertMessage:@"昵称不可以超过20字"] animated:YES completion:nil];
            return NO;
        }
    }
    
    
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (textField.text.length == 0) {
        textField.text = self.userInfo[@"nickname"];
    }
    return YES;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [textView resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    self.isTeturn = 1;
    
    if (textView.text.length > 250) {
        [self presentViewController:[LZCTools alertMessage:@"编辑不可以超过250字"] animated:YES completion:nil];
        [textView resignFirstResponder];
        return;
    }
    
    [textView flashScrollIndicators];   // 闪动滚动条
    
    //    static CGFloat maxHeight = 130.0f;
    static CGFloat maxHeight = 500.0f;
    CGRect frame = textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [textView sizeThatFits:constraintSize];
    if (size.height >= maxHeight)
    {
        size.height = maxHeight;
        textView.scrollEnabled = YES;   // 允许滚动
    }
    else
    {
        textView.scrollEnabled = NO;    // 不允许滚动，当textview的大小足以容纳它的text的时候，需要设置scrollEnabed为NO，否则会出现光标乱滚动的情况
    }
    textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
    
    if ([textView isEqual:[self.view viewWithTag:16]]) {
        
        
        _scorllView.contentSize = CGSizeMake(SCREEN_WIDTH, textView.y+textView.height);
    }
}

- (void)completeAction:(UIButton *)sender {
    NSLog(@"完成信息编辑");
    
    if (_isChangeImage) {
        // 上传图片如果尚未成功，就重新执行此方法 延时
        if (self.imgStr.length == 0) {
            [self performSelector:@selector(completeAction:) withObject:nil afterDelay:1.0f];
            return;
        }
    }
    
    NSDictionary *paramDict = @{@"nickname":((UITextField *)[self.view viewWithTag:11]).text,
                                @"intro":((UITextView *)[self.view viewWithTag:15]).text,
                                @"face":self.imgStr,
                                @"sex":self.sexT,
                                @"birthday":self.birthdayStr,
                                //                                     @"age":self.ageStr,
                                @"city":self.locationStr,
                                @"pro_intro":((UITextView *)[self.view viewWithTag:16]).text};
    
    // PUT /users 修改用户信息 nickname 用户昵称 intro 用户简介 face 头像图片地址
    [[NetworkTool sharedTool] requestWithName:@"修改用户信息" URLString:APIUser parameters:paramDict method:@"PUT" callBack:^(id responseObject) {
        // 同步本地用户信息
        NSDictionary *userDict = [responseObject valueForKey:@"data"];
        SetUserDefaule(userDict, USERINFO);
        
        self.isTeturn = 0;
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
}

- (void)sexAction:(UIButton *)sender {
    NSLog(@"修改性别");
    
    self.isTeturn = 1;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改性别" message:nil preferredStyle:UIAlertControllerStyleAlert];
    //    [alert addAction:[UIAlertAction actionWithTitle:@"保密" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //        [sender setTitle:@"保密" forState:UIControlStateNormal];
    //        self.sexT = @"0";
    //    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [sender setTitle:@"男" forState:UIControlStateNormal];
        self.sexT = @"1";
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [sender setTitle:@"女" forState:UIControlStateNormal];
        self.sexT = @"2";
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (void)headPicAction:(UIButton *)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改个人头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"从相册中选择");
        self.isTeturn = 1;
        self.picker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        self.picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:self.picker.sourceType];
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"拍照");
        self.isTeturn = 1;
        self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        self.picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:self.picker.sourceType];
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];}

- (void)certifyAction:(id)sender
{
	CertifySelectViewController *certVC = [[CertifySelectViewController alloc] init];
	certVC.userInfo = _userInfo;
	[self.navigationController pushViewController:certVC animated:YES];
}

#pragma mark ==========照相机相册功能==========
/**
 *  配置图片选择器
 */
-(void)createImgPicker {
    self.picker = [[UIImagePickerController alloc]init];
    self.picker.delegate = self;
    self.picker.allowsEditing = YES;
	self.picker.navigationBar.tintColor = [UIColor blackColor];
}

/**
 *  当用户选取完成后调用
 *
 *  @param picker 图片选择器对象
 *  @param info   返回用户所选择的媒体信息
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    // 判断选择的媒体类型是否为图片
    if ([mediaType isEqualToString:@"public.image"]) {
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
            
            //如果是 来自照相机的image，那么先保存
            UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
            UIImageWriteToSavedPhotosAlbum(original_image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            
        }
        
        //获得编辑过的图片
        UIImage *image = [[info objectForKey: @"UIImagePickerControllerEditedImage"] copy];
        
        [self updateCover:image];
        
        UIButton *imgBtn = [self.view viewWithTag:10];
        [imgBtn setImage:image forState:UIControlStateNormal];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
}

/**
 *  将图片保存到iPhone本地相册
 *  UIImage *image            图片对象
 *  id completionTarget       响应方法对象
 *  SEL completionSelector    方法
 *  void *contextInfo
 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"照片已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"照片保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    
}
//如果这是一个modalViewController，需要dismiss 它发了个cancel消息，必须关闭它
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark ==========网络请求==========
- (void)updateCover:(UIImage *)img {
    
    self.isChangeImage = 1;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
    
    // 请求头
    [afn.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
    NSDictionary *dict = @{
                           @"file[]":@[]
                           };
    
    [afn POST:APIImages parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
        // 这里的_photoArr是你存放图片的数组
        NSData *imageData = UIImageJPEGRepresentation(img, 0.8);
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
        /*
         *该方法的参数
         1. appendPartWithFileData：要上传的照片[二进制流]
         2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
         3. fileName：要保存在服务器上的文件名
         4. mimeType：上传的文件的类型
         */
        [formData appendPartWithFileData:imageData name:@"pic[]" fileName:fileName mimeType:@"image/jpeg"]; //
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
        //        return [obj valueForKey:@"payload"];
        NSArray *imgArr = [[[obj valueForKey:@"payload"] valueForKey:@"data"] valueForKey:@"images"];
        NSLog(@"上传图片 success = %@", imgArr);
        self.imgStr = imgArr[0];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传图片 failure = %@", error);
        [self presentViewController:[LZCTools AFNErrorAlert:error] animated:YES completion:nil];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (NSMutableArray *)ageArr {
    if (_ageArr == nil) {
        _ageArr = [[NSMutableArray alloc] init];
        for (int i = 1; i < 101; i++) {
            [_ageArr addObject:[NSString stringWithFormat:@"%d", i]];
        }
    }
    return _ageArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

